<template>
  <div>
    <!-- -->
    <div class="container">
      <el-steps :active="active" style="margin: 10px 0">
        <el-step title="基本信息" icon="el-icon-edit"></el-step>
        <el-step title="商品SKU" icon="el-icon-menu"></el-step>
        <el-step title="商品详情" icon="el-icon-picture"></el-step>
      </el-steps>
      <BasicProduct v-if="active==1" ref="BasicProduct" v-model="BasicProductFrom"></BasicProduct>
      <Sku v-if="active==2" ref="sku" v-model="skuFrom"></Sku>
      <ProductDetali ref="ProductDetali" v-if="active==3" v-model="ProductDetaliFrom"></ProductDetali>
      <div style="width: 100%;text-align: center">
        <el-button style="margin: 0 5px" @click="back" v-if="active!=1">上一步</el-button>
        <el-button style="margin: 0 5px" @click="next" v-if="active!=3">下一步</el-button>
        <el-button style="margin: 0 5px" type="primary" @click="submitForm"
          v-if="active==3 && updateOrAdd ==1">添加商品</el-button>
        <el-button style="margin: 0 5px" type="primary" @click="submitForm"
          v-if="active==3 && updateOrAdd ==2">修改商品</el-button>
      </div>
    </div>
  </div>
</template>
<script>
  import log from "@/views/monitor/job/log";
  import BasicProduct from './component/BasicProduct.vue';
  import Sku from './component/Sku.vue';
  import ProductDetali from "./component/ProductDetali";
  import { addProduct, getProduct, updateProduct } from "@/api/shopping/product";

  export default {
    name: 'addPro',
    components: { BasicProduct, Sku, ProductDetali },
    data() {
      return {
        updateOrAdd: 1,//1添加 2修改
        active: 1,
        BasicProductFrom: {
          name: undefined,
          description: undefined,
          price: undefined,
          promotionPrice: undefined,
          serviceIds: undefined,
          stock: undefined,
          lowStock: undefined,
          status: undefined,
          regionId: null,
          brandId: null,
          giftPoint: null,
          promotionType: 0,
          /** 阶梯数据 */
          ladderArr: [
            {
              count: 0,
              discount: 0
            },
          ],
          /** 满减数据 */
          fullArr: [
            {
              fullPrice: 0,
              reducePrice: 0
            }
          ]
        },
        skuFrom: {
          defaultImg: "",
          albumPics: [],
          showTable: false,
          columns: [
            { label: '销售价格', prop: 'salePrice' },
            { label: '促销价格', prop: 'promotionPrice' },
            { label: '商品库存', prop: 'stock' },
            { label: '库存预警值', prop: 'warningStock' }
          ],
          tableData: [],
        },
        ProductDetaliFrom: {
          productHtml: ""
        }
      };
    },
    computed: {},
    mounted() {
      if (this.$route.query.id) {
        //获取修改数据
        this.getProdoctData(this.$route.query.id)
        this.updateOrAdd = 2
      } else {
        this.updateOrAdd = 1
      }
    },
    methods: {
      async getProdoctData(id) {
        let res = await getProduct(id)
        if (res.code == 200) {
          // 商品基本信息
          this.initUpdatePro(res)
          //  商品sku
          this.initUpdateSku(res)
          //初始化
          this.ProductDetaliFrom.productHtml = res.data.productHtml
        }

      },
      initUpdateSku(res) {
        this.skuFrom.defaultImg = res.data.defaultImg
        this.skuFrom.albumPics = res.data.albumPics.split(',').map(item => {
          return {
            url: item,
            name: item
          }
        })
        if (res.data.skuList.length != 0) {
          this.skuFrom.showTable = true
          //  处理sku
          //   1.1处理表头
          let defaultCol = [{ label: '销售价格', prop: 'salePrice' },
          { label: '促销价格', prop: 'promotionPrice' },
          { label: '商品库存', prop: 'stock' },
          { label: '库存预警值', prop: 'warningStock' }]
          //转json
          let skuList = [];
          res.data.skuList.forEach(item => {
            skuList.push(...JSON.parse(item.spData))
          })
          let key = this.uniqueKeys(skuList)
          let newCol = key.map(item => {
            return { label: item, prop: item }
          })
          this.skuFrom.columns = [...newCol, ...defaultCol]
          //处理table数据
          res.data.skuList.forEach(item => {
            let obj = {
              salePrice: item.price,
              promotionPrice: item.promotionPrice,
              stock: item.stock,
              warningStock: item.warningStock
            }
            let skuAttr = this.deTransformData(JSON.parse(item.spData))
            //合并
            obj = { ...obj, ...skuAttr }
            this.skuFrom.tableData.push(obj)
          })
        }
      },
      initUpdatePro(res) {
        this.BasicProductFrom.name = res.data.name
        this.BasicProductFrom.description = res.data.description
        this.BasicProductFrom.price = res.data.price
        this.BasicProductFrom.promotionPrice = res.data.promotionPrice
        // this.BasicProductFrom.serviceIds = res.data.serviceIds.split(',')
        this.BasicProductFrom.serviceIds = res.data.serviceIds.split(',').map(Number);
        this.BasicProductFrom.stock = res.data.stock
        this.BasicProductFrom.lowStock = res.data.lowStock
        this.BasicProductFrom.status = res.data.status
        this.BasicProductFrom.regionId = res.data.regionId
        this.BasicProductFrom.brandId = res.data.brandId
        this.BasicProductFrom.giftPoint = res.data.giftPoint
        this.BasicProductFrom.promotionType = res.data.promotionType
        this.BasicProductFrom.id = res.data.id
        if (res.data.promotionType == 1) {
          res.data.ladderArr.forEach(item => {
            this.BasicProductFrom.ladderArr = []
            // 阶梯
            this.BasicProductFrom.ladderArr.push({
              id: item.id,
              count: item.count,
              discount: item.discount
            })
          })
          //初始话满减
          this.BasicProductFrom.fullArr.push(
            {
              fullPrice: 0,
              reducePrice: 0
            }
          )
        } else if (res.data.promotionType == 2) {
          this.BasicProductFrom.fullArr = []
          // 满减
          res.data.fullArr.forEach(item => {
            // 满减
            this.BasicProductFrom.fullArr.push({
              id: item.id,
              fullPrice: item.fullPrice,
              reducePrice: item.reducePrice
            })
          })
          //初始话阶梯
          this.BasicProductFrom.ladderArr.push(
            {
              count: 0,
              discount: 0
            }
          )
        } else {
          this.BasicProductFrom.ladderArr.push(
            {

              count: 0,
              discount: 0
            }
          )
          this.BasicProductFrom.fullArr.push(
            {
              fullPrice: 0,
              reducePrice: 0
            }
          )
        }
      },
      next() {
        this.active += 1
        // if (this.active == 1) {
        //   this.$refs.BasicProduct.validateForm().then(() => {
        //     this.active += 1
        //   })
        // } else if (this.active == 2) {
        //   this.$refs.sku.validateForm().then(() => {
        //     this.active += 1
        //   })
        // }
      },
      back() {
        if (this.active > 1) {
          this.active--;
        }
      },
      uniqueKeys(data) {
        const keysSet = new Set();
        data.forEach(item => {
          keysSet.add(item.key);
        });
        return Array.from(keysSet);
      },
      transformData(row) {
        const excludeKeys = ['promotionPrice', 'salePrice', 'stock', 'warningStock'];
        const result = [];
        for (const key in row) {
          if (row.hasOwnProperty(key) && !excludeKeys.includes(key)) {
            result.push({ key, value: row[key] });
          }
        }
        return result;
      },
      deTransformData(data) {
        const result = {};
        for (const item of data) {
          result[item.key] = item.value;
        }
        return result;
      },
      handleFromData() {
        let from = { ...this.BasicProductFrom };
        // 处理sku数据
        let skuList = []
        this.skuFrom.tableData.forEach(item => {
          skuList.push({
            price: item.salePrice,
            promotionPrice: item.promotionPrice,
            stock: item.stock,
            lowStock: item.warningStock,
            spData: JSON.stringify(this.transformData(item))
          })
        });
        // 处理图片 [1,2,2].join()
        let arrImages = []
        this.skuFrom.albumPics.forEach(item => {
          arrImages.push(item.url)
        })
        from.albumPics = arrImages.join()
        from.defaultImg = this.skuFrom.defaultImg
        from.productHtml = this.ProductDetaliFrom.productHtml
        from.skuList = skuList
        from.serviceIds = from.serviceIds.join()
        return from;
      },
      submitForm() {
        let from = this.handleFromData()
        //调用接口
        if (this.updateOrAdd == 1) {//添加
          addProduct(from).then(res => {
            if (res.code == 200) {
              this.BasicProductFrom = Object.assign(this._data.BasicProductFrom, this.$options.data()
                .BasicProductFrom)
              this.skuFrom = Object.assign(this._data.skuFrom, this.$options.data()
                .skuFrom)
              this.$refs.ProductDetali.reset()
              this.active = 1
              this.$message({
                type: 'success',
                message: '添加成功'
              })
            }
          })
        } else if (this.updateOrAdd == 2) {
          updateProduct(from).then(res => {
            if (res.code == 200) {
              this.BasicProductFrom = Object.assign(this._data.BasicProductFrom, this.$options.data()
                .BasicProductFrom)
              this.skuFrom = Object.assign(this._data.skuFrom, this.$options.data()
                .skuFrom)
              this.$refs.ProductDetali.reset()
              this.active = 1
              this.$message({
                type: 'success',
                message: '修改成功'
              })
            }
          })
        }

      }

    },
  };
</script>
<style lang="css" scoped>
  .container {
    width: 960px;
    min-height: 100vh;
    border: 1px solid gainsboro;
    margin: 20px auto;
    padding: 20px;
  }
</style>